package cn.logic.network

import cn.swu.Waimai.logic.network.MenuService
import cn.swu.Waimai.logic.network.ServiceCreator
import cn.swu.Waimai.logic.network.UserService
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import java.lang.RuntimeException
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException
import kotlin.coroutines.suspendCoroutine
object UserNetwork {



    private val userService = ServiceCreator.create(UserService::class.java)

    private val menuService = ServiceCreator.create(MenuService::class.java)

    //2
    suspend fun getLocation(token:String) = userService.getLocation(token).await()


    //获得菜单
    suspend fun getGoodsList(id: String) = menuService.getGoodsList(id).await()


    //搜索结果
    suspend fun searchGoods(key: String) = menuService.searchGoods(key).await()
//    协程处理回调
    private suspend fun <T> Call<T>.await(): T{
        return suspendCoroutine { continuation ->
        enqueue(object : Callback<T>{
            override fun onResponse(call: Call<T>, response: Response<T>) {
                val body = response.body()
                if (body != null) continuation.resume(body)
                else continuation.resumeWithException(
                    RuntimeException("Response Body Is Null!")
                )
            }

            override fun onFailure(call: Call<T>, t: Throwable) {
                continuation.resumeWithException(t)
            }
        })
        }
    }
}